import {fileURLToPath, URL} from 'node:url'

import {defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import eslintPlugin from 'vite-plugin-eslint'
import {viteMockServe} from 'vite-plugin-mock'

import AutoImport from 'unplugin-auto-import/vite' // 自动导入
import Components from 'unplugin-vue-components/vite' // 组件注册
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers' // elementPlus
import Icons from 'unplugin-icons/vite' // icon相关
import IconsResolver from 'unplugin-icons/resolver'
import copy from 'rollup-plugin-copy'
import defaultSettings from './mock/setting.js'
import {isCustomElement} from 'leafer-vue/compiler'


// https://vitejs.dev/config/
export default defineConfig(({mode}) => {
    //获取各种环境下的对应的变量
    // 根据当前工作目录中的 `mode` 加载 .env 文件
    // 设置第三个参数为 '' 来加载所有环境变量，而不管是否有 `VITE_` 前缀。
    const env = loadEnv(mode, process.cwd())
    return {
        base: env.VITE_PUBLIC_PATH, //打包base路径
        // 生产环境打包配置
        build: {
            target: 'modules',
            outDir: 'D:/nginxsys/leaflet', //指定输出路径
            assetsDir: 'static', // 指定生成静态资源的存放路径
            minify: 'terser', // 混淆器，terser构建后文件体积更小
            emptyOutDir: true, // 构建时清空该目录
            terserOptions: {
                compress: {
                    drop_console: false,
                    drop_debugger: false
                }
            },
            rollupOptions: {
                output: {
                    chunkFileNames: 'js/[name]-[hash].js',
                    entryFileNames: 'js/[name]-[hash].js',
                    manualChunks(id) {
                        if (id.includes('node_modules')) {
                            const arr = id.toString().split('node_modules/')
                            return arr[arr.length - 1].split('/')[0].toString()
                        }
                    }
                }
            }
        },
        // 启动服务配置
        server: {
            host: '0.0.0.0',
            port: 8000,
            open: true,
            https: false,
            proxy: !defaultSettings.isMockData && {
                '/auth': {
                    target: 'http://192.168.0.111:8083/',
                    // target: 'http://rongheng.imwork.net:3808/',
                    changeOrigin: true, // 允许跨域
                    // rewrite: path => path.replace(/^\/api/, ''),// 替换路径
                    bypass(req, res, options) {
                        const proxyUrl = new URL(req.url || '', (options.target))?.href || ''
                        console.log('接口地址:' + proxyUrl)
                        // req.headers['x-proxy-Url'] = proxyUrl// 设置无效
                        res.setHeader('x-proxy-Url', proxyUrl)// 设置有效
                    }
                },
                '/smooth': {
                    target: 'http://192.168.0.111:8083/',
                    // target: 'http://rongheng.imwork.net:3808/',
                    changeOrigin: true,
                    bypass(req, res, options) {
                        const proxyUrl = new URL(req.url || '', (options.target))?.href || ''
                        console.log('接口地址:' + proxyUrl)
                        // req.headers['x-proxy-Url'] = proxyUrl// 设置无效
                        res.setHeader('x-proxy-Url', proxyUrl)// 设置有效
                    }
                },
                '/tmms': {
                    target: 'http://192.168.0.111:8083/',
                    // target: 'http://rongheng.imwork.net:1808/',
                    changeOrigin: true,
                    bypass(req, res, options) {
                        const proxyUrl = new URL(req.url || '', (options.target))?.href || ''
                        console.log('接口地址:' + proxyUrl)
                        // req.headers['x-proxy-Url'] = proxyUrl// 设置无效
                        res.setHeader('x-proxy-Url', proxyUrl)// 设置有效
                    }
                },
                '/cmms_schedule': {
                    target: 'http://192.168.0.111:8083/',
                    // target: 'http://rongheng.imwork.net:1808/',
                    changeOrigin: true,
                    bypass(req, res, options) {
                        const proxyUrl = new URL(req.url || '', (options.target))?.href || ''
                        console.log('接口地址:' + proxyUrl)
                        // req.headers['x-proxy-Url'] = proxyUrl// 设置无效
                        res.setHeader('x-proxy-Url', proxyUrl)// 设置有效
                    }
                },
                '/gis': {
                    target: 'http://192.168.0.111:8083/',
                    // target: 'http://rongheng.imwork.net:1808/',
                    changeOrigin: true,
                    bypass(req, res, options) {
                        const proxyUrl = new URL(req.url || '', (options.target))?.href || ''
                        console.log('接口地址:' + proxyUrl)
                        // req.headers['x-proxy-Url'] = proxyUrl// 设置无效
                        res.setHeader('x-proxy-Url', proxyUrl)// 设置有效
                    }
                }
            }
        },
        plugins: [
            vue({
                template: {
                    compilerOptions: {
                        isCustomElement
                    }
                }
            }),
            vueJsx(),
            copy({
                targets: [
                    {src: './node_modules/libpag/lib/libpag.wasm', dest: 'public/'}
                ],
                hook: process.env.NODE_ENV === 'production' ? 'writeBundle' : 'buildStart'
            }),
            eslintPlugin({
                include: ['src/**/*.js', 'src/**/*.vue'],
                cache: true
            }),
            AutoImport({
                imports: ['vue', '@vueuse/core', 'pinia', 'vue-router'],
                dirs: ['src/utils', 'src/store'],
                dts: fileURLToPath(new URL('src/types/auto-imports.d.ts', import.meta.url)),
                resolvers: [
                    ElementPlusResolver(),
                    // 自动导入图标
                    IconsResolver({
                        prefix: 'Icon'
                    })
                ]
            }),
            Components({
                dirs: ['src/views', 'src/layout', 'src/components'],
                dts: fileURLToPath(new URL('src/types/components.d.ts', import.meta.url)),
                resolvers: [
                    ElementPlusResolver(),
                    IconsResolver({
                        enabledCollections: ['ep'] // 重点
                    })
                ]
            }),
            Icons({
                autoInstall: true
            }),
            defaultSettings.isMockData && viteMockServe({
                // mockPath: path.resolve(process.cwd(), 'src/mock'),
                mockPath: './mock',
                localEnabled: env.VITE_NODE_ENV === 'development', // 只在本地开发打开，正式使用的时候注释下面这条，打开当前这条
                // localEnabled: true, // 设置是否启用本地模拟.ts文件，不要在生产环境中打开
                prodEnabled: env.VITE_NODE_ENV === 'development', // 只在本地开发打开，正式使用的时候注释下面这条，打开当前这条
                // prodEnabled: true, // 设置打包是否启用 mock 功能
                injectCode: `
            import { setupProdMockServer } from './mockProdServer';
            setupProdMockServer();
          `
            })
        ],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url))
            },
            extensions: ['.vue', '.js'] // 忽略后缀名的配置选项, 添加 .vue .js后缀
        }
    }
})
